package icu.gking.cart_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import icu.gking.cart_system.common.Result;
import icu.gking.cart_system.dto.CommodityAddDTO;
import icu.gking.cart_system.dto.CommodityListDTO;
import icu.gking.cart_system.pojo.Cart;
import icu.gking.cart_system.pojo.Commodity;
import icu.gking.cart_system.pojo.User;
import icu.gking.cart_system.service.CartService;
import icu.gking.cart_system.service.CommodityService;
import icu.gking.cart_system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/commodity")
@CrossOrigin  // 允许跨域请求
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private UserService userService;

    @Autowired
    private CartService cartService;

    @PostMapping("/add")
    public Result<Commodity> addCommodity(@RequestBody CommodityAddDTO commodityAddDTO) {
        try {
            // 参数校验
            if (commodityAddDTO.getCommodityName() == null || commodityAddDTO.getCommodityName().trim().isEmpty()) {
                return Result.error("商品名称不能为空");
            }
            if (commodityAddDTO.getPrice() == null || commodityAddDTO.getPrice() <= 0) {
                return Result.error("商品价格必须大于0");
            }
            if (commodityAddDTO.getStock() == null || commodityAddDTO.getStock() < 0) {
                return Result.error("商品库存不能为负数");
            }
            if (commodityAddDTO.getSellerId() == null) {
                return Result.error("卖家ID不能为空");
            }

            // 创建商品对象
            Commodity commodity = new Commodity();
            BeanUtils.copyProperties(commodityAddDTO, commodity);
            commodity.setStatus(1); // 设置商品状态为上架

            // 保存商品
            boolean saved = commodityService.save(commodity);
            if (saved) {
                return Result.success(commodity);
            } else {
                return Result.error("添加商品失败");
            }
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 买家查看所有上架商品
     */
    @GetMapping("/list")
    public Result<List<CommodityListDTO>> list() {
        try {
            // 获取商品列表
            List<Commodity> commodities = commodityService.list();
            
            // 获取所有相关的卖家ID
            Set<Integer> sellerIds = commodities.stream()
                    .map(Commodity::getSellerId)
                    .collect(Collectors.toSet());
            
            // 批量查询卖家信息并创建最终的Map
            final Map<Integer, String> sellerMap = new HashMap<>();
            if (!sellerIds.isEmpty()) {
                List<User> sellers = userService.listByIds(sellerIds);
                sellerMap.putAll(sellers.stream()
                        .collect(Collectors.toMap(User::getUserId, User::getUserName)));
            }
            
            // 转换为DTO并设置卖家名称
            List<CommodityListDTO> result = commodities.stream().map(commodity -> {
                CommodityListDTO dto = new CommodityListDTO();
                BeanUtils.copyProperties(commodity, dto);
                dto.setSellerName(sellerMap.getOrDefault(commodity.getSellerId(), "未知商家"));
                return dto;
            }).collect(Collectors.toList());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取商品列表失败", e);
            return Result.error("获取商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 商家查看自己的商品
     */
    @GetMapping("/seller/{sellerId}")
    public Result<List<CommodityListDTO>> listSellerCommodities(@PathVariable Integer sellerId) {
        try {
            // 验证卖家身份
            User seller = userService.getById(sellerId);
            if (seller == null || seller.getRole() != 1) {
                return Result.error("无效的商家ID");
            }

            // 查询该商家的所有商品
            QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("seller_id", sellerId);
            List<Commodity> commodities = commodityService.list(queryWrapper);

            // 转换为DTO
            List<CommodityListDTO> dtoList = commodities.stream().map(commodity -> {
                CommodityListDTO dto = new CommodityListDTO();
                BeanUtils.copyProperties(commodity, dto);
                dto.setSellerName(seller.getUserName());
                // 确保状态是整数类型
                dto.setStatus(commodity.getStatus());
                log.info("商品转换 - ID: {}, 称: {}, 状态: {}, 状态类型: {}", 
                    dto.getCommodityId(), 
                    dto.getCommodityName(),
                    dto.getStatus(),
                    dto.getStatus() != null ? dto.getStatus().getClass().getName() : "null");
                return dto;
            }).collect(Collectors.toList());

            return Result.success(dtoList);
        } catch (Exception e) {
            log.error("获取商家商品列表失败", e);
            return Result.error("获取商家商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 编辑商品信息
     */
    @PutMapping("/update")
    public Result<Commodity> updateCommodity(@RequestBody CommodityAddDTO commodityAddDTO) {
        try {
            // 参数校验
            if (commodityAddDTO.getCommodityName() == null || commodityAddDTO.getCommodityName().trim().isEmpty()) {
                return Result.error("商品名称不能为空");
            }
            if (commodityAddDTO.getPrice() == null || commodityAddDTO.getPrice() <= 0) {
                return Result.error("商品价格必须大于0");
            }
            if (commodityAddDTO.getStock() == null || commodityAddDTO.getStock() < 0) {
                return Result.error("商品库存不能为负数");
            }

            // 查询原有商品
            Commodity commodity = commodityService.getById(commodityAddDTO.getCommodityId());
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            // 更新商品信息
            BeanUtils.copyProperties(commodityAddDTO, commodity);
            
            if (commodityService.updateById(commodity)) {
                log.info("商品更新成功 - 商品ID: {}", commodity.getCommodityId());
                return Result.success(commodity);
            } else {
                log.error("商品更新失败 - 商品ID: {}", commodity.getCommodityId());
                return Result.error("更新商品失败");
            }
        } catch (Exception e) {
            log.error("更新商品时发生异常", e);
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 下架商品
     */
    @PostMapping("/offline/{commodityId}")
    public Result<Boolean> offlineCommodity(@PathVariable Integer commodityId) {
        try {
            log.info("接收到下架请求 - 商品ID: {}", commodityId);

            // 查询商品
            Commodity commodity = commodityService.getById(commodityId);
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            // 设置商品状态为下架(0)
            commodity.setStatus(0);
            
            // 执行更新操作
            if (commodityService.updateById(commodity)) {
                log.info("商品下架成功 - 商品ID: {}", commodityId);
                return Result.success(true);
            } else {
                log.error("商品下架失败 - 商品ID: {}", commodityId);
                return Result.error("下架商品失败");
            }
        } catch (Exception e) {
            log.error("下架商品发生异常", e);
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/{commodityId}")
    public Result<CommodityListDTO> getCommodityDetail(@PathVariable Integer commodityId) {
        try {
            // 查询商品信息
            Commodity commodity = commodityService.getById(commodityId);
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            // 查询卖家信息
            User seller = userService.getById(commodity.getSellerId());
            if (seller == null) {
                return Result.error("卖家信息不存在");
            }

            // 转换为DTO
            CommodityListDTO dto = new CommodityListDTO();
            BeanUtils.copyProperties(commodity, dto);
            dto.setSellerName(seller.getUserName());

            return Result.success(dto);
        } catch (Exception e) {
            return Result.error("获取商品详情失败：" + e.getMessage());
        }
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/update/status")
    public Result<Boolean> updateCommodityStatus(@RequestBody Map<String, Object> params) {
        try {
            log.info("接收到更新状态请求参数: {}", params);
            
            // 获取商品ID
            Integer commodityId = params.get("commodityId") == null ? null : 
                Integer.valueOf(params.get("commodityId").toString());
            Integer status = params.get("status") == null ? null :
                Integer.valueOf(params.get("status").toString());

            // 参数校验
            if (commodityId == null) {
                return Result.error("商品ID不能为空");
            }

            // 查询商品
            Commodity commodity = commodityService.getById(commodityId);
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            log.info("更新商品状态 - 商品ID: {}, 当前状态: {}, 新状态: {}", 
                    commodityId, commodity.getStatus(), status);

            // 设置商品状态
            commodity.setStatus(status != null ? status : 0);
            
            if (commodityService.updateById(commodity)) {
                log.info("商品状态更新成功 - 商品ID: {}, 新状态: {}", commodityId, commodity.getStatus());
                return Result.success(true);
            } else {
                log.error("商品状态更新失败 - 商品ID: {}", commodityId);
                return Result.error("更新状态失败");
            }
        } catch (Exception e) {
            log.error("更新商品状态时发生异常", e);
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{commodityId}")
    public Result<Boolean> deleteCommodity(@PathVariable Integer commodityId) {
        try {
            // 检查商品是否存在
            Commodity commodity = commodityService.getById(commodityId);
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            // 先删除购物车中的相关记录
            QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
            cartQueryWrapper.eq("commodity_id", commodityId);
            cartService.remove(cartQueryWrapper);

            // 再删除商品
            boolean removed = commodityService.removeById(commodityId);
            if (removed) {
                return Result.success(true);
            } else {
                return Result.error("删除商品失败");
            }
        } catch (Exception e) {
            log.error("删除商品失败 - commodityId: {}", commodityId, e);
            return Result.error("删除商品失败：" + e.getMessage());
        }
    }
} 